#include "includes.h"
void sys_error(const char *e)
{
    perror(e);
    exit(1);
}
void fn(char *p);

int main(int argc ,char** argv)
{
    int serversocket  =  socket(AF_INET,SOCK_STREAM,0);
    if(serversocket ==-1){
        sys_error("socket error");
    }
    struct sockaddr_in  addr ;
    memset(&addr,0,sizeof(addr));
    addr.sin_family =AF_INET;
    addr.sin_port = htons(9000);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int r;	
    // int r=  inet_pton(AF_INET,"127.0.0.1",&(addr.sin_addr.s_addr));
    // if(r ==0){
    //     sys_error("inet_pton");
    // }
    r= bind(serversocket,(struct sockaddr*)&addr,sizeof(addr));
    if(r == -1){
        sys_error("bind");
    }
    listen(serversocket,10);
    struct sockaddr_in  client;
    socklen_t  l =sizeof(client);
    int fd ;
    while (1)
    {
        
        memset(&client,0,sizeof(client));
        fd = accept(serversocket,(struct sockaddr*)&client,&l);
        if(fd ==-1){
            sys_error("accept error");
        }
        char buf[100];
        CLEAR_ARRAY(buf);
        printf("New connection from IP:%s,port:%d\n",inet_ntop(AF_INET,&(client.sin_addr),buf,sizeof(buf)),ntohs(client.sin_port));
        while(1){
            CLEAR_ARRAY(buf);
            r= read(fd,buf,sizeof(buf));
            if(r == 0  ){
            	printf("client disconnected\n");
                close(fd);
                break;
            }
            else if(r ==-1){
                sys_error("read error");
            }
            write(STDOUT_FILENO,buf,r);
            fn(buf);
            write(fd,buf,r);
        }
    }
    close(fd);
    return 0;
}
void fn(char *p)
{
    if(!p){
        return;
    }
    while (*p)
    {
        *p =toupper(*p);
        p++;
    }
    
}
